package com.liuche.book.gateway.filter;

import cn.dev33.satoken.stp.StpUtil;
import com.liuche.framework.common.constant.GlobalConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author：liuche
 * @Date：2024年07月07日 15:31
 * @Description：将userId带到下游服务
 */
@Component
@Slf4j
public class AddUserIdHeaderFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("==================> TokenConvertFilter");

        String userId;
        try {
            userId = StpUtil.getLoginIdAsString();
        } catch (Exception e) {
            return chain.filter(exchange);
        }

        log.info("## 当前登录的用户 ID: {}", userId);
        ServerWebExchange newExchange = exchange.mutate()
                .request(builder -> builder.header(GlobalConstants.HEADER_USER_ID, userId)) // 将用户 ID 设置到请求头中
                .build();

        return chain.filter(newExchange);
    }
}
